<?php

namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use common\components\helpers\Util;
use common\components\services\message\ManualWechatMessage;
use common\models\datas\Customer;
use common\models\datas\CustomerSubscribe;
use common\models\datas\Site;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\News;
use EasyWeChat\Message\Text;
use webback\models\data\Website;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\data\Pagination;
use yii\helpers\Json;
use yii\web\BadRequestHttpException;
use yii\widgets\ActiveForm;

class SubscribeController extends \zhtfrontend\components\bases\BaseController
{

    public function actionIndex()
    {
        $param['searchData'] = \Yii::$app->request->get();
        $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
        $data = CustomerSubscribe::find()->where(['site_id' => Fun::getSiteId()])->orderBy('subscribe_time DESC');
        if (!empty($param['searchData'])) {
            $search_data = array_filter($param['searchData']);
            if (!empty($search_data['nickname'])) {
                $data->andWhere(['like', 'nickname', $search_data['nickname']]);
            }
            if (!empty($search_data['is_subscribe'])) {
                $data->andWhere(['is_subscribe' => $search_data['is_subscribe']]);
            }
            if (!empty($search_data['searchDate'])) {
                $data->andWhere(['between', 'subscribe_time', strtotime($search_data['searchDate']), strtotime(date('Y-m-d', strtotime("+1 day", strtotime($search_data['searchDate']))))]);
            }
        }
        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        $array = Fun::asArray($model, ['operate']);
        foreach ($array as $k => $arr) {
            $array[$k]['is_register'] = '否';
            $code = Util::zeroFill((string)17, '3') . $arr['openid'];
            $customer = Customer::findOne(['zhtopenid' => $code]);
            if ($customer != null)
                $array[$k]['is_register'] = '是';
        }

        return $this->render('index', ['data' => $array, 'pages' => $pages]);
    }

    public function actionImport($nextOpenId = null)
    {
        $options = \Yii::$app->params['options_zht'];
        $app = new Application($options);
        $userService = $app->user;
        $user = $userService->lists($nextOpenId);
        $openids = $user->data['openid'];
        $c_openids = CustomerSubscribe::find()->select('openid')->where(['site_id' => Fun::getSiteId()])->column();

        //编辑已取消关注
        $update_no = [];
        $yes_openids = CustomerSubscribe::find()->select('openid')->where(['is_subscribe' => 1, 'site_id' => Fun::getSiteId()])->column();
        if ($yes_openids) {
            foreach ($yes_openids as $o_openid) {
                if (!in_array($o_openid, $openids)) {
                    $update_no[] = $o_openid;
                }
            }
            if (!empty($update_no)) {
                CustomerSubscribe::updateAll(['is_subscribe' => 2, 'updated_at' => time(), 'site_id' => Fun::getSiteId()], ['openid' => $update_no]);
            }
        }
        //编辑取消以后又关注的
        $update_yes = [];
        $no_openids = CustomerSubscribe::find()->select('openid')->where(['is_subscribe' => 2, 'site_id' => Fun::getSiteId()])->column();
        if ($no_openids) {
            foreach ($no_openids as $y_openid) {
                if (in_array($y_openid, $openids)) {
                    $update_yes[] = $y_openid;
                }
            }
            if (!empty($update_yes)) {
                CustomerSubscribe::updateAll(['is_subscribe' => 1, 'updated_at' => time(), 'site_id' => Fun::getSiteId()], ['openid' => $update_yes]);
            }
        }

        //新关注插入
        $data = [];
        if ($openids) {
            foreach ($openids as $openid) {
                if (!in_array($openid, $c_openids)) {
                    $data[] = $openid;
                }
            }
        }
        if (!empty($data)) {
            $new_arr = array_chunk($data, 100);
            foreach ($new_arr as $arr) {
                $user_list = $userService->batchGet($arr);
                $info = $user_list->user_info_list;
                $insert = [];
                foreach ($info as $k => $val) {
                    $insert[$k]['nickname'] = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '@', $val['nickname']);
                    $insert[$k]['openid'] = $val['openid'];
                    $insert[$k]['sex'] = $val['sex'];
                    $insert[$k]['province'] = $val['province'];
                    $insert[$k]['city'] = $val['city'];
                    $insert[$k]['headimgurl'] = $val['headimgurl'];
                    $insert[$k]['subscribe_time'] = $val['subscribe_time'];
                    $insert[$k]['groupid'] = $val['groupid'];
                    $insert[$k]['remark'] = $val['remark'];
                    $insert[$k]['unionid'] = isset($val['unionid']) ? $val['unionid'] : '';
                    $insert[$k]['created_at'] = time();
                    $insert[$k]['is_subscribe'] = 1;
                    $insert[$k]['site_id'] = Fun::getSiteId();
                }
                Fun::getSysDb()->createCommand()->batchInsert('{{%customer_subscribe}}', ['nickname', 'openid', 'sex', 'province', 'city', 'headimgurl', 'subscribe_time', 'groupid', 'remark', 'unionid', 'created_at', 'is_subscribe', 'site_id'], $insert)->execute();
            }
        }
        $count = count($data);
        if (count($openids) >= 10000) {
            $this->actionImport($user->next_openid);
        }
        return $this->redirectMessage(\Yii::t('zhtfrontend', '成功导入' . $count . '条'), Fun::url(['subscribe/index']));
    }

    public function actionTransfergroup()
    {
        $post = \Yii::$app->request->post();
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $ajax_object = new AjaxObject();
        if (empty($post['id'])) {
            $ajax_object->data = 0;
            $ajax_object->content = '系统错误刷新页面重试1';
            return $ajax_object;
        }
        $id = (int)$post['id'];
        $groupId = (int)$post['groupid'];
        $model = CustomerSubscribe::findOne($id);
        if ($model == null) {
            $ajax_object->data = 0;
            $ajax_object->content = '系统错误刷新页面重试';
            return $ajax_object;
        }
        $options = \Yii::$app->params['options_zht'];
        $app = new Application($options);
        $group = $app->user_group;
        $result = $group->moveUser($model->openid, $groupId);
        if ($result->errcode == 0 && $result->errmsg === 'ok') {
            $model->groupid = $groupId;
            $model->save(false);
            if ($groupId == 2) {

                $site = Site::findOne(Fun::getSiteId());
                $website = (new \yii\db\Query())->from('{{%website}}')->select('name')->where(['id' => $site->web_site_id])->one(Fun::getSiteDatabases());
                //发消息
                $message = new Text(['content' => "豆苗朵教育产业微信公众平台已开放使用一段时间了，为保证各位用户的正常浏览，更好地了解平台的使用，现通知提醒大家：豆苗朵教育产业共同体目前所运营的公众平台只为$website[name]地区的用户提供会员服务，非本地区不予提供服务。如因微信地区未设置成”$website[name]”造成误屏蔽不能访问的情况，请在微信公众号中留言，我们将会重新审核并于三个工作日内予以回复。\n感谢所有用户对豆苗朵教育产业共同体微信公众平台的关注与支持！"]);
                $app->staff->message($message)->to($model->openid)->send();
            }
            $ajax_object->data = 1;
            $ajax_object->content = 'ok';
        } else {
            $ajax_object->data = 0;
            $ajax_object->content = '系统错误刷新页面重试';
        }
        return $ajax_object;
    }

    public function actionGroup()
    {
        $options = \Yii::$app->params['options'];
        $app = new Application($options);
        $group = $app->user_group;
        $group_list = $group->lists();
        print_r($group_list);
        die;

    }


    public function actionBatchgroup()
    {
        $options = \Yii::$app->params['options_zht'];
        $app = new Application($options);
        $group = $app->user_group;
        $openids = CustomerSubscribe::find()->select('openid')->where(['is_subscribe' => 1])->column();
        $i = 0;
        $arr_count = count($openids);
        for ($i = 0; $i < $arr_count; $i = $i + 50) {
            $data_arr[] = array_slice($openids, $i, 50);
        }
        foreach ($data_arr as $data) {
            $result = $group->moveUsers($data, 101);
        }
        if ($result->errcode == 0) {
            CustomerSubscribe::updateAll(['groupid' => 101, 'site_id' => Fun::getSiteId()], ['openid' => $openids]);
            return $this->redirectMessage(\Yii::t('zhtfrontend', '批量操作成功'), Fun::url(['subscribe/index']));

        }
        return $this->redirectMessage(\Yii::t('zhtfrontend', '批量操作成功'), Fun::url(['subscribe/index']));

    }
}
